package com.dragon.framework.config;

import com.dragon.common.utils.ThreadUtils;
import com.dragon.framework.decorator.MdcTaskDecorator;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 *
 * @author dragon
 * @version 1.0
 * @date 2024/7/15 17:05
 */
@Configuration
public class ThreadPoolConfig {

    /**
     * 核心线程池大小
     */
    private final int corePoolSize = Runtime.getRuntime().availableProcessors() + 1;

    /**
     * 最大可创建的线程数
     */
    private final int maxPoolSize = corePoolSize * 2;

    /**
     * 队列最大长度
     */
    private static final int QUEUE_CAPACITY = 1000;

    /**
     * 线程池维护线程所允许的空闲时间
     */
    private static final int KEEP_ALIVE_SECONDS = 300;
    /**
     * 线程池前缀
     */
    private static final String THREAD_NAME_PREFIX = "TaskExecutor-";


    @Bean(name = "threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数量，线程池创建时候初始化的线程数
        executor.setMaxPoolSize(maxPoolSize);
        // 最大线程数，只有在缓冲队列满了之后才会申请超过核心线程数的线程
        executor.setCorePoolSize(corePoolSize);
        // 缓冲队列，用来缓冲执行任务的队列
        executor.setQueueCapacity(QUEUE_CAPACITY);
        // 当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
        executor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS);
        // 配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix(THREAD_NAME_PREFIX);
        // 线程池对拒绝任务的处理策略：这里采用了CallerRunsPolicy策略，当线程池没有处理能力的时候，该策略会直接在 execute 方法的调用线程中运行被拒绝的任务；如果执行程序已关闭，则会丢弃该任务
        // DiscardPolicy: 直接丢弃
        // CallerRunsPolicy：不在新线程中执行任务，而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        // 配置MDC装饰器
        executor.setTaskDecorator(new MdcTaskDecorator());

        return executor;
    }

    /**
     * 执行周期性或定时任务
     */
    @Bean(name = "scheduledExecutorService")
    protected ScheduledExecutorService scheduledExecutorService() {
        return new ScheduledThreadPoolExecutor(corePoolSize,
            new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build(),
            new ThreadPoolExecutor.CallerRunsPolicy()) {
            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                super.afterExecute(r, t);
                ThreadUtils.printException(r, t);
            }
        };
    }

}
